package cn.fenqing.druid.core;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * @author fenqing
 */
public class DataSourceFactory {

    private volatile static DataSource DATA_SOURCE;

    public static DataSource getDataSource() {
        if (DATA_SOURCE == null) {
            synchronized (DataSourceFactory.class) {
                if (DATA_SOURCE == null) {
                    DATA_SOURCE = createDataSource();
                    return DATA_SOURCE;
                }
            }
        }
        return DATA_SOURCE;
    }

    private static DataSource createDataSource() {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        URL resource = contextClassLoader.getResource("druid.properties");
        if (resource == null) {
            throw new RuntimeException("未找到druid.properties配置文件");
        }
        Properties properties = new Properties();
        try (
                InputStream inputStream = resource.openStream()
        ) {
            properties.load(inputStream);
            return DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException("创建数据源失败");
        }
    }


}
